package com.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class FTPClientImp implements FTPClientInterface{
	
	private String ipAddress;
	private int port;
	private String user;
	static Logger logger = LogManager.getLogger(FTPClientImp.class.getName());
	
	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	private String pass;
	
	private FTPClient ftpClient;
	
	public String getIpAddress() {
		return ipAddress;
	}

	public void setIpAddress(String ipAddress) {
		this.ipAddress = ipAddress;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	@Override
	public int upLoadFile(String fileName, String remotePath) {
		if(connect()){
			try {
				System.out.println(fileName+" "+remotePath);
				ftpClient.changeWorkingDirectory(remotePath);
				InputStream input = new FileInputStream(new File(fileName));
				ftpClient.storeFile(remotePath, input);
				System.out.println("success");
			} catch (Exception e) {
				logger.error("File transfer failed. ");
			}
		}  else {
			System.out.println("faield");
			logger.error("FTP Client Connect failed. ");
		}
		return 0;
	}

	@Override
	public int downLoadFile(String fileName) {
		return 0;
	}

	@Override
	public boolean connect() {
		ReaderConfig.initConfigVariable();
		boolean result = false;
		int reply;
		ftpClient = new FTPClient();
		int i = 0;
		if(ftpClient.isAvailable()){
			return true;
		}
		while(i<3){
			try {
				ftpClient.connect(ReaderConfig.getFtpIpAddress(), ReaderConfig.getFtpPort());
				ftpClient.login(ReaderConfig.getFtpUserName(), ReaderConfig.getFtpPasswd());
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				reply = ftpClient.getReplyCode();
				if(!FTPReply.isPositiveCompletion(reply)){
					ftpClient.disconnect();
					System.err.println("FTP server refused connected. ");
					i++;
				} else {
					result = true;
					break;
				}
			} catch (IOException e) {
				i++;
				e.printStackTrace();
				logger.error("ftp connect faield. ");
				result = false;
			}
		}
		return result;
	}

	@Override
	public boolean closeFtpClient() {
		boolean result = false;
		try {
			if(ftpClient.logout()){
				result = true;
				System.out.println("log out sucess.");
			} 
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}


	public void Test(){
		logger.error("this is a tests. ");
	}
	public static void main(String args[]){
		new FTPClientImp().Test();
	}
}
